package mh.demo.jdk.util.concurrent;

import mh.demo.PrintUtils;

import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 《Java并发编程艺术》书中的线程间交换数据的示例
 */
public class ExchangerDemo {
    private static final Exchanger<String> exgr = new Exchanger<>();
    private static final ExecutorService threadPool = Executors.newFixedThreadPool(2);

    public static void main(String[] args) {
        threadPool.execute(() -> {
            try {
                String A = "银行流水A";
                final String B = exgr.exchange(A);
                PrintUtils.println("B录入是：" + B);
            } catch (InterruptedException ignored) {
            }
        });
        threadPool.execute(() -> {
            try {
                String B = "银行流水B";
                String A = exgr.exchange(B);
                PrintUtils.println("A 和 B 数据是否一致：" + A.equals(B) + "，A录入的是：" + A + "，B录入是：" + B);
            } catch (InterruptedException ignored) {
            }
        });
        threadPool.shutdown();
    }
}
